package com.demo.send;

import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Collection;

import org.apache.log4j.Logger;

import com.demo.bean.Enviroment;
import com.demo.util.FileBackup;
import com.demo.util.FileNameEnums;

public class SendImpl implements Isend {

	private static final Logger logger = Logger.getLogger(SendImpl.class);
	
	@SuppressWarnings("unchecked")
	public void send(Collection<Enviroment> collection) {
		
		try {
			Object object = FileBackup.recover(FileNameEnums.CLIENT_DATA_PATH.getPath(),true);
			if(object != null) {
				collection.addAll((Collection<? extends Enviroment>) object);
			}
			logger.info("正在与服务端建立连接..");
			Socket socket = new Socket("127.0.0.1", 9999);
			logger.info("与服务器建立成功！");
			ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
			
			logger.info("正在发送数据..");
			oos.writeObject(collection);
			oos.flush();
			oos.close();
			logger.info("数据发送完毕！");
			
			socket.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("连接数据库失败....");
			try {
				FileBackup.store(FileNameEnums.CLIENT_DATA_PATH.getPath(), collection);
				logger.info("备份已经成功的数据...");
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				logger.info("数据备份失败...");
			}
		}
		
	}

}
